import { Button, Space, Upload } from 'ant-design-vue'
import { defineComponent, PropType, ref } from 'vue'

import { orderApi } from '@/apis'
import { ActivityPeople } from '@/apis/orderTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { useDialog } from '@/hooks'

export default defineComponent({
  name: 'PeopleList',
  props: {
    peoples: {
      type: Array as PropType<Array<ActivityPeople>>,
      required: true
    }
  },
  emits: ['dataCallback'],
  setup(props, { emit }) {
    const { showConfirm } = useDialog()
    const peopleList = ref(props.peoples as any[])
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: 400,
      options: {
        border: true,
        align: 'center',
        columns: [
          {
            title: '姓名',
            field: 'name',
            width: 150
          },
          {
            title: '手机号',
            field: 'phone',
            width: 200
          },
          {
            title: '操作',
            slots: {
              default: 'operation'
            },
            width: 100
          }
        ]
      }
    } as ProTableProps)

    /** 上传 */
    async function handleUploadData(file) {
      try {
        peopleList.value = await orderApi.activityImport(file)
        handleCallback()
      } finally {
      }
    }

    function handleDeleteUser(row) {
      showConfirm({
        content: '确认删除该用户？',
        onOk: () => {
          peopleList.value = peopleList.value.filter(val => {
            return val.id != row.id
          })
          handleCallback()
        }
      })
    }

    function handleCallback() {
      const peopleId = peopleList.value.map(val => {
        return val.id
      })
      emit('dataCallback', peopleId)
    }

    function handleRefresh(data) {
      peopleList.value = data
    }

    return {
      peopleList,
      tableRef,
      tableConfig,
      handleUploadData,
      handleDeleteUser,
      handleRefresh
    }
  },
  render() {
    return (
      <div>
        <Upload
          accept=".xlsx,.xls"
          name="file"
          customRequest={this.handleUploadData}
          showUploadList={false}
        >
          <Button type="primary">导入</Button>
        </Upload>
        <ProTable
          ref="tableRef"
          data={this.peopleList}
          v-show={this.peopleList.length > 0}
          style={{ width: '450px', marginTop: '10px' }}
          v-slots={{
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDeleteUser(row)}
                >
                  删除
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
